package com.zxing.android;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.activity.BaseActivity;
import com.da.lon.wang.xlg.activity.ProductsActivity;
import com.da.lon.wang.xlg.activity.WebViewActivity;
import com.da.lon.wang.xlg.bean.LineBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.zxing.android.camera.CameraManager;
import com.zxing.android.decoding.CaptureActivityHandler;
import com.zxing.android.decoding.InactivityTimer;
import com.zxing.android.view.ViewfinderView;

import net.tsz.afinal.http.AjaxParams;

import java.io.IOException;
import java.util.Vector;

public class CaptureActivity extends BaseActivity implements Callback,
        android.view.View.OnClickListener {
    public static final String QR_RESULT = "RESULT";
    private static final long VIBRATE_DURATION = 200L;
    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            try {
                mediaPlayer.seekTo(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private SurfaceView surfaceView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private boolean vibrate;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            requestWindowFeature(Window.FEATURE_NO_TITLE);

            setContentView(R.layout.activity_capture);
            surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
            viewfinderView = (ViewfinderView) findViewById(R.id.viewfinderview);

            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

            hasSurface = false;
            inactivityTimer = new InactivityTimer(this);

            ((ImageButton) findViewById(R.id.image)).setVisibility(View.GONE);
            ((RelativeLayout) findViewById(R.id.top_rl))
                    .setBackgroundColor(Color.parseColor("#2e2e2e"));
            TextView title = (TextView) findViewById(R.id.title);
            title.setText("二维码");
            title.setTextColor(Color.parseColor("#ffffff"));
            ImageButton back = (ImageButton) findViewById(R.id.back);
            back.setImageResource(R.drawable.xlg_back_white);
            back.setOnClickListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            cameraManager = new CameraManager(getApplication());

            viewfinderView.setCameraManager(cameraManager);

            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            if (hasSurface) {
                initCamera(surfaceHolder);
            } else {
                surfaceHolder.addCallback(this);
                surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            }
            decodeFormats = null;
            characterSet = null;

            playBeep = true;
            AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
            if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
                playBeep = false;
            }
            initBeepSound();
            vibrate = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (handler != null) {
                handler.quitSynchronously();
                handler = null;
            }
            cameraManager.closeDriver();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            inactivityTimer.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            cameraManager.openDriver(surfaceHolder);
            if (handler == null) {
                handler = new CaptureActivityHandler(this, decodeFormats,
                        characterSet);
            }
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            if (!hasSurface) {
                hasSurface = true;
                initCamera(holder);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    public void handleDecode(Result obj, Bitmap barcode) {
        try {
            inactivityTimer.onActivity();
            playBeepSoundAndVibrate();
            showResult(obj, barcode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showResult(final Result rawResult, Bitmap barcode) {
        try {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);

            final String result = rawResult.getText();

            if (result.startsWith("http")) {

                try {
                    if (result.contains(".hhecz.")) {
                        String url = rawResult.getText();
                        if (url.contains("/p/")) {
                            String product_number = url.substring(
                                    url.indexOf("/p/") + 3,
                                    url.indexOf(".html"));
                            Intent intent = new Intent(CaptureActivity.this,
                                    ProductsActivity.class);
                            PreferenceUtils.getInstance().SetSettingString(
                                    PreferencesConfig.PRODUCT_NUMBER,
                                    product_number);
                            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                            this.startActivity(intent);
                        } else {
                            Intent intent = new Intent(CaptureActivity.this,
                                    WebViewActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putInt("flag", 001);
                            bundle.putString("url", rawResult.getText());
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                        finish();
                    } else {
                        builder.setTitle("打开网址有风险，是否打开？\n" + result);
                        builder.setPositiveButton("打开网址",
                                new OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        dialog.dismiss();
                                        Intent intent = new Intent(
                                                CaptureActivity.this,
                                                WebViewActivity.class);
                                        Bundle bundle = new Bundle();
                                        bundle.putInt("flag", 001);
                                        bundle.putString("url", result);
                                        intent.putExtras(bundle);
                                        startActivity(intent);
                                        finish();
                                    }
                                });
                        builder.setNegativeButton("取消", new OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                                finish();
                            }
                        });
                        builder.setCancelable(false);
                        builder.show();
                    }
                } catch (Exception e) {
                    Toast.makeText(CaptureActivity.this, "地址有误",
                            Toast.LENGTH_SHORT).show();
                    finish();
                }

            } else {
                checkLine(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理条形码
     */
    private void checkLine(String code) {
        try {
            String url = XLGConstants.URL + "Ok-barcode";

            HttpLoader<LineBean> httpLoader = new HttpLoader<LineBean>(this,
                    url, LineBean.class);
            AjaxParams params = new AjaxParams();
            params.put(
                    "id",
                    PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.USER_ID, ""));
            params.put(
                    "user_key",
                    PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.USER_KEY, ""));
            params.put(
                    "token",
                    XLGDataUtils.encrypt2MD5("Ok" + XLGConstants.SECRET
                            + "barcode"));
            params.put("device_type", "1");
            params.put("code", code);
            httpLoader.setManagerListener(new OnWebLoadListener<LineBean>() {

                @Override
                public void OnStart() {
                    showDialog("查询中");

                }

                @Override
                public void OnError(String error) {
                    Toast.makeText(CaptureActivity.this, "查询失败",
                            Toast.LENGTH_SHORT).show();
                    finish();
                }

                @Override
                public void onSuccess(LineBean t) {
                    if (t != null) {
                        if (t.getCode().equals("000000")
                                && t.getResult() != null
                                && t.getResult().getUrl() != null) {

                            String url = t.getResult().getUrl();
                            String product_number = url.substring(
                                    url.indexOf("/p/") + 3,
                                    url.indexOf(".html"));

                            Intent intent = new Intent(CaptureActivity.this,
                                    ProductsActivity.class);
                            PreferenceUtils.getInstance().SetSettingString(
                                    PreferencesConfig.PRODUCT_NUMBER,
                                    product_number);
                            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                            startActivity(intent);

                            finish();
                        } else {
                            Toast.makeText(CaptureActivity.this,
                                    t.getMessage(), Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    } else {
                        Toast.makeText(CaptureActivity.this, "查询失败",
                                Toast.LENGTH_SHORT).show();
                        finish();
                    }

                }
            });
            httpLoader.loadData(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(MessageIDs.restart_preview, delayMS);
        }
    }

    private void initBeepSound() {
        try {
            if (playBeep && mediaPlayer == null) {
                setVolumeControlStream(AudioManager.STREAM_MUSIC);
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setOnCompletionListener(beepListener);

                try {
                    AssetFileDescriptor fileDescriptor = getAssets().openFd(
                            "qrbeep.ogg");
                    this.mediaPlayer.setDataSource(
                            fileDescriptor.getFileDescriptor(),
                            fileDescriptor.getStartOffset(),
                            fileDescriptor.getLength());
                    this.mediaPlayer.setVolume(0.1F, 0.1F);
                    this.mediaPlayer.prepare();
                } catch (IOException e) {
                    this.mediaPlayer = null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void playBeepSoundAndVibrate() {
        try {
            if (playBeep && mediaPlayer != null) {
                mediaPlayer.start();
            }
            if (vibrate) {
                Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                vibrator.vibrate(VIBRATE_DURATION);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult(RESULT_CANCELED);
            finish();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_FOCUS
                || keyCode == KeyEvent.KEYCODE_CAMERA) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
        }

    }

}